﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace BReusable
{

	/// <summary>
	/// For dynamically building HTML
	/// using MVC's TagBuilder class as a model
	/// </summary>
	/// <remarks>http://www.asp.net/LEARN/mvc/tutorial-35-cs.aspx</remarks>
	public class HtmlTagBuilder
	{
		private const string StrCssClass = "class";
		private readonly string _tag;
		public string Tag { get { return _tag; } }
		private readonly Dictionary<string, string> _attributes = 
			new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);

		public string CssClass { get
		{
			return _attributes != null && _attributes.ContainsKey(StrCssClass)?
			       		_attributes[StrCssClass]: string.Empty;
		}
			set { _attributes[StrCssClass] = value; }
		}
		
		public string InnerHtml { get; set; }
		public bool DoNotSelfCloseOnEmptyInner { get; set; }

		public void MergeAttribute(string attribute, string value)
		{
		
			_attributes.Add(attribute,TransformAttributeValue( value));
		}

		public HtmlTagBuilder (string tag)
		{
			_tag=tag;
		}

			public override string ToString()
			{
				if (InnerHtml.IsNullOrEmpty() && DoNotSelfCloseOnEmptyInner == false)
					return "<" + Tag + AddCssClass() + "/>";

				return HtmlOpenTag(Tag,AddCssClass()+AddAttributes()) + InnerHtml + HtmlCloseTag(Tag);
			}

			private string AddAttributes()
			{
				if ( _attributes.Count > 0)
				{
					
					return kljlkj;
				}
				return string.Empty;
			}
			private string AddCssClass()
			{
				return CssClass != null ? ' '+StrCssClass+'=' + CssClass : string.Empty;
			}

			private static string HtmlOpenTag(string tag, string attributes)
			{
				return "<" + tag + attributes ?? string.Empty + ">";
			}
			private static string HtmlCloseTag( string tag)
			{
				return "</" + tag + ">";
			}

		/// <summary>
		/// Takes the attribute string and tries to ensure it meets the HTML standards
		/// </summary>
		/// <param name="value"></param>
		/// <returns></returns>
			/// <remarks>based off of http://www.w3schools.com/html/html_attributes.asp</remarks>
		private string TransformAttributeValue(string value)
		{
			if(value.StartsWith("\"") && value.EndsWith("\""))
				return value;
			if (value.StartsWith("'") && value.EndsWith("'"))
				return value;
			if (value.Contains("\""))
				return "'" + value + "'";
			return "\"" + value + "\"";
		}
	}
}
